<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------

namespace Kcdns\Service\Sms;

/**
 * 短信驱动 基类
 *
 * @package Service\Sms
 *
 */
abstract class DriverBase
{
    //短信接口地址
    protected $api_url = "";
    //driver config
    protected $params = array();
    //错误信息
    protected $error = "";
    //错误编码
    protected $error_code = "";

    //http错误编码
    protected $http_code = "";

    //构造函数
    public function __construct($apiUrl, $params = array())
    {
        $this->api_url = $apiUrl;
        $this->params = $params;
    }

    /**
     * 驱动响应
     * @param type $sendStatus
     * @param type $response
     * @param type $errCode
     * @param type $error
     * @return array  array(
     *                  'status'=>'发送状态',
     *                  'errorCode'=>'错误码',
     *                  'error'=>'错误信息',
     *                  ’response'=>'接口完整响应'
     * )
     */
    public function parseResponse($sendStatus, $response, $errCode, $error)
    {
        $this->error_code = $errCode;
        $this->error = $error;
        return array(
            'status' => $sendStatus,
            'errorCode' => $errCode,
            'error' => $error,
            'response' => $response,
        );
    }

    public function http_get($url, $params, $headers = [])
    {
        $ch = curl_init();
        $url = $url . '?' . http_build_query($params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge([], $headers));
        $result = curl_exec($ch);
        curl_close($ch);
        $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $result;
    }

    public function http_post($url, $params)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $result;
    }

    //发送短信
    abstract public function send($mobile, $content);
}
